import { createSlice } from "@reduxjs/toolkit"; 
import { store } from './store'
import { reqCategory1, reqCategory2, reqCategory3 } from "@/api/category/categort"
import type {IResCategory} from '@/api/category/model/categoryTypes'

// 状态数据接口
interface AttrState {
    category1list: IResCategory[] 
    category2list: IResCategory[]
    category3list: IResCategory[]
  }
  
  // 默认值
  let initialState:AttrState= {
      category1list: [] ,
      category2list: [], 
      category3list: []
    }
    // 创建切片对象
const categorySlice = createSlice({
    //  别名
    name: 'category',
    initialState,
    // 修改数据的方法
    reducers: {
        // 修改的方法
        // action方法：type:动作类型，payload：动作的值
        changecategorylist: (state,{payload})=>{
            state.category1list = payload
            
        },
        // 修改二级分类的方法
        changecategory2List: (state,{payload})=>{
            state.category2list=payload
        },
        // 修改二级分类的方法
        changecategory3List: (state,{payload})=>{
            state.category3list=payload
        }

    }
})
// 提取action方法
let { changecategorylist, changecategory2List,changecategory3List } = categorySlice.actions
// 异步调用方法
 export const asyncCategoryList = () => {
    return async ()=> {
        let res = await reqCategory1()        
        // 调用方法更新数据
        store.dispatch(changecategorylist(res.data))
    }
}
export const asyncCategory2List = (id:number) => {
    return async ()=> {
        let res = await reqCategory2(id)
        // console.log(res1)
        store.dispatch(changecategory2List(res.data))
    }
}
export const asyncCategory3List = (id:number) => {
    return async ()=> {
        let res = await reqCategory3(id)
        store.dispatch(changecategory3List(res.data))
    }
}

export default categorySlice.reducer